package jdbc02;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;

/**
 * 模拟用户登录来演示SQL注入
 */
public class JDBCDemo02 {
    public static void main(String[] args) throws Exception {
        //利用scanner来模拟用户的输入动作
        Scanner scan = new Scanner(System.in);
        System.out.println("请输入用户名：");
        String username = scan.next();
        System.out.println("请输入密码：");
        String password = scan.next();

        //2.利用SQL语句来比对用户录入的用户名密码和数据库表中已有的用户名和密码
        Class.forName("com.mysql.jdbc.Driver");
        Connection coon = DriverManager.getConnection("jdbc:mysql://localhost:3306/test02?useSSL=false", "root", "root");
        Statement statement = coon.createStatement();
        String sql = "SELECT * FROM `user` WHERE uname = '" + username + "'AND password = '" + password + "'";
        /*
        *   1'or'1 = 1 当这样输入密码时，会导致虽然密码不正确，但是先and后or导致结果正确，where后限制条件一直满足，利用createStatement向数据库管理系统发送SQL,可能出现SQL注入
        * */
        ResultSet resultSet = statement.executeQuery(sql);
        while (resultSet.next()) {
            System.out.println(resultSet.getString("uname") + " " + resultSet.getString("password"));
        }

    }
}
